﻿#region

using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using ThuySan.Bussiness;
using ThuySan.Models;

#endregion

namespace ThuySan.Controllers
{
    public class AccountController : Controller
    {
        private readonly UnitOfWork unitOfWork = new UnitOfWork();

        public ActionResult LogOn()
        {
            if (User.Identity.IsAuthenticated)
                return RedirectToAction("Index", "Admin", new
                {
                    area = "Backend"
                });
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(string username, string password, bool remember, string returnUrl)
        {
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                WebUser user = unitOfWork.UserRepository.Select(c => c.UserName == username && c.Password == password).FirstOrDefault();
                if (user != null)
                {
                    FormsAuthentication.SetAuthCookie(username, remember);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    return RedirectToAction("Index", "Admin", new
                    {
                        area = "Backend"
                    });
                }
            }
            return View();
        }
    }
}
